package com.ws.mymedia;

import com.ws.mymedia.fragments.MusicFragment;
import com.ws.mymedia.fragments.VideoFragment;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.Menu;

public class MediaHomeActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_media_home);

		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayShowTitleEnabled(true);
		
		createTab(actionBar, R.string.music_title, new MediaTabListener<MusicFragment>("music", MusicFragment.class));
		createTab(actionBar, R.string.video_title, new MediaTabListener<VideoFragment>("video", VideoFragment.class));
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_media_home, menu);
		return true;
	}
	
	private void createTab(ActionBar actionBar, int name, TabListener tabListener) {
		Tab musicTab = actionBar.newTab().setText(name).setTabListener(tabListener);
		actionBar.addTab(musicTab);
	}
	
	private class MediaTabListener<T extends Fragment> implements TabListener {
		
		private String tag;
		private Fragment fragment;
		private Class<T> fragmentClass;
		
		public MediaTabListener(String tag, Class<T> fragmentClass) {
			this.tag = tag;
			this.fragmentClass = fragmentClass;
		}
		
		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			
		}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			 // Check if the fragment is already initialized
	        if (fragment == null) {
	            // If not, instantiate and add it to the activity
	            fragment = Fragment.instantiate(MediaHomeActivity.this, fragmentClass.getName());
	            ft.add(android.R.id.content, fragment, tag);
	        } else {
	            // If it exists, simply attach it in order to show it
	            ft.attach(fragment);
	        }
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			 if (fragment != null) {
		            // Detach the fragment, because another one is being attached
		            ft.detach(fragment);
		        }
		}
		
	}

}
